package com.cdu.xinmiao.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.cdu.xinmiao.R;
import com.cdu.xinmiao.data.DatabaseHelper;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;

public class LoginActivity extends AppCompatActivity {
    private EditText etStudentNumber, etPhoneNumber, etVerifyCode;
    private SuperButton btnLogin;
    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.login), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getId();

        bindClick();

    }

    private void bindClick() {
        // 设置登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入的学号、手机号和验证码
                String studentNumber = etStudentNumber.getText().toString().trim();
                String phoneNumber = etPhoneNumber.getText().toString().trim();
                String verifyCode = etVerifyCode.getText().toString().trim();

                // 进行登录验证
                boolean isValid = validateInputs(studentNumber, phoneNumber, verifyCode);

                Log.d("LoginActivity", "isValid: " + isValid);

                if (isValid) {
                    performLogin(studentNumber, phoneNumber, verifyCode);
                } else {
                    Toast.makeText(LoginActivity.this, "请输入正确的学号、手机号和验证码", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    // 验证输入的学号、手机号和验证码是否合法
    private boolean validateInputs(String studentNumber, String phoneNumber, String verifyCode) {
        return !studentNumber.isEmpty() && !phoneNumber.isEmpty() && !verifyCode.isEmpty();
    }

    // 执行登录操作的方法
    private void performLogin(String studentNumber, String phoneNumber, String verifyCode) {
        if (loginSuccess(studentNumber, phoneNumber, verifyCode)) {
            etPhoneNumber.setText("");
            etVerifyCode.setText("");
            etVerifyCode.setText("");

            logStudentLogin(studentNumber);

            // 登录成功，跳转到主界面

            Intent intent = new Intent(LoginActivity.this, IdentifyActivity.class);
            startActivity(intent);
        } else {
            etPhoneNumber.setText("");
            etVerifyCode.setText("");
            etVerifyCode.setText("");

            // 登录失败，显示错误提示
            Toast.makeText(LoginActivity.this, "登录失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean loginSuccess(String studentNumber, String phoneNumber, String verifyCode) {
        // 这里仅作示例，直接返回true表示登录成功
        // Todo 上传身份证/录取通知书验证身份
        dbHelper = new DatabaseHelper(this);

        // 获取可写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        Cursor cursor = db.query(
                "Students",
                new String[]{"StudentID"},
                "StudentNumber = ?",
                new String[]{studentNumber},
                null,
                null,
                null
        );

        boolean isSuccess = cursor.moveToFirst();
        cursor.close();
        return isSuccess;
    }

    private void getId() {
        etStudentNumber = findViewById(R.id.et_student_number);
        etPhoneNumber = findViewById(R.id.et_phone_number);
        etVerifyCode = findViewById(R.id.et_verify_code);
        btnLogin = findViewById(R.id.btn_login);
    }

    private void logStudentLogin(String studentNumber) {
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        values.put("StudentNumber", studentNumber);
//        values.put("LoginTime", System.currentTimeMillis()); // 使用当前时间作为登录时间
//        db.insert("LoginLog", null, values);

        Log.d("Login: ", "Student " + studentNumber + " logged in.");
    }
}